import { View, Text, Input } from "@tarojs/components";
import './index.scss'
import Taro from "@tarojs/taro";
import Portrait from "../../components/Portrait";
import { STATUS, STATUS_NAME } from "../../configProvider";
import { useState } from "react";
const SelectStatus = () => {
  const [code, setCode] = useState('');

  const ackChange = (status: STATUS) => {
    console.log('Clicked', STATUS_NAME[status]);
    Taro.showModal({
      title: `选择"${STATUS_NAME[status]}"?`,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          Taro.cloud.callFunction({
            // 要调用的云函数名称
            name: 'verifyCode',
            // 传递给云函数的event参数
            data: {
              status: status,
              code: code,
            }
          }).then(res => {
            console.log('verifyCode result', res.result);
            if (!res.result) {
              Taro.showToast({
                title: 'Code错误',
                icon: 'error',
                duration: 1000
              })
              return;
            }
            doChange(status, code, res.result.name);
          }).catch(err => {
            console.log('Fail to call verifyCode', err)
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });

  }
  const doChange = (status: STATUS, code: string, name: string) => {

    Taro.setStorage({
      key: 'status',
      data: status
    });
    Taro.setStorage({
      key: 'code',
      data: code
    });
    Taro.setStorage({
      key: 'name',
      data: name
    });
    Taro.showToast({
      title: '切换成功',
      icon: 'success',
      duration: 1000
    })
    setTimeout(() => {
      Taro.reLaunch({ url: '../index/index' });
    }, 1000);
  }

  return <>
    <View className="common-title">请选择身份</View>
    <View className="status-options">
      <View className="status-option-1" onClick={() => ackChange(STATUS.STUDENT)}>
        <Portrait status={STATUS.STUDENT} size={150} />
      </View>
      <View className="status-option-2" onClick={() => ackChange(STATUS.TEACHER)}>
        <Portrait status={STATUS.TEACHER} size={150} />
      </View>
      <View className="status-option-3" onClick={() => ackChange(STATUS.ADMIN)}>
        <Portrait status={STATUS.ADMIN} size={150} />
      </View>
      <View className="status-option-4" onClick={() => ackChange(STATUS.INSTRUCTOR)}>
        <Portrait status={STATUS.INSTRUCTOR} size={150} />
      </View>
    </View>
    <Text className="common-title">若非学生,请填写Code验证身份</Text>
    <View className="common-card input-container">
      <Text>Code: </Text>
      <Input value={code} className="input" onInput={(e: any) => { setCode(e.target.value) }} />
    </View>
  </>
}
export default SelectStatus;
